//
//  FileManager.m
//  keyboard
//
//  Created by 遇水 on 16/3/13.
//  Copyright © 2016年 遇水. All rights reserved.
//

#import "FileManager.h"
#import "FaceModel.h"
#import "MJExtension.h"

@implementation FileManager


+(instancetype)sharedFileManager
{
    
    static FileManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[FileManager alloc]init];
    });
    return manager;
}



-(BOOL)isFileName:(NSString *)fileUrl
{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:fileUrl]) {
        return YES;
    }
    return NO;
}




-(void)createFileName:(NSString *)fileUrl
{
    //创建一个plist文件
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"EmotionIcons" ofType:nil];
    
   BOOL result =  [manager createFileAtPath:[path stringByAppendingPathComponent:fileUrl] contents:nil attributes:nil];
 
}



-(BOOL)deleteFileName:(NSString *)fileUrl
{
    NSError *err;
    BOOL result;
    NSFileManager *manage = [NSFileManager defaultManager];
    if ([manage fileExistsAtPath:fileUrl]) {
        
     result =   [manage removeItemAtPath:fileUrl error:&err];
    }
    
    return result;
}

/**
 *  保存到最近使用的
 *
 *  @param model face对象
 *
 *  @return 保存结果
 */
-(BOOL)saveFace:(FaceModel *)model
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"EmotionIcons/newly/info.plist" ofType:nil];
    //读取出所有的表情数据，将新插入的表情数据放在最前面
    NSMutableArray *array =(NSMutableArray *)[FaceModel objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:path]];
    //获得数据
    
    //判断当前的这个对象是否已经存在一个内容相同的对象了
    for (FaceModel *m in array) {
        if (m.png != nil) {
            //说明已经存在了
            if (model.png == m.png) {
                [array removeObject:m];
                continue;
            }
        }
        
        if (m.code != nil) {
            if (model.code == m.code) {
                [array removeObject:m];
                continue;
            }
        }
    }
    
    
    [array insertObject:model atIndex:0];
    
    //将模型数组转化为字典数组
    NSArray *dicArray = [FaceModel keyValuesArrayWithObjectArray:array];
    return [dicArray writeToFile:path atomically:YES];
    
}

/**
 *  自定义face
 *
 *  @param facemodel
 *
 *  @return 
 */
-(void)addCustomFace:(FaceModel *)model
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"EmotionIcons/custom/info.plist" ofType:nil];
    NSMutableArray *array = (NSMutableArray *)[FaceModel objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:path]];
    //获得数据
    [array insertObject:model atIndex:0];
    
    //将模型数组转化为字典数组
    NSArray *dicArray = [FaceModel keyValuesArrayWithObjectArray:array];
    
    [dicArray writeToFile:path atomically:YES];
    
   
}


@end
